<script setup lang="ts">
import { addEnterpriseAPI, editEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI } from '@/apis/enterprise';
import type { AddEnterpriseData, Industry } from '@/types/enterprise';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref } from 'vue';
import { uploadFileAPI } from '@/apis/common';
import { CircleCheck, Upload } from '@element-plus/icons-vue';
import { useRoute, useRouter } from 'vue-router';

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<AddEnterpriseData>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: undefined // 营业执照id
})

// 获取行业列表
const industryList = ref<Industry[]>([])
const getIndustryList = async () => {
  const { data } = await getIndustryListAPI()
  industryList.value = data
}
getIndustryList()

// 上传营业执照
const fileList = ref<UploadUserFile[]>([])
// 上传之前检查类型和大小
const beforeUpload = (rawFile: UploadRawFile) => {
  console.log(rawFile);
  if (['image/jpeg', 'image/png'].includes(rawFile.type) === false) {
    ElMessage.error('文件扩展名需为.png .jpg .jpeg!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('文件大小不得超过5MB!')
    return false
  }
  return true
}
// 删除时清空对应的图片信息
const removeFile = () => {
  addForm.value.businessLicenseUrl = ''
  addForm.value.businessLicenseId = undefined
  // 主动触发规则校验
  addFormRef.value?.validateField('businessLicenseUrl')
}
// 自定义上传事件
const uploadFile = async (options: UploadRequestOptions) => {
  // 准备formdata对象
  const fd = new FormData()
  // 根据后端要求添加字段
  fd.append('file', options.file)
  fd.append('type', 'businessLicense')
  // 调用接口上传文件
  const res = await uploadFileAPI(fd)
  // 保存营业执照 url 和 id，用于添加企业
  addForm.value.businessLicenseId = res.data.id
  addForm.value.businessLicenseUrl = res.data.url
  // 主动触发规则校验
  addFormRef.value?.validateField('businessLicenseUrl')
  // 存储到 fileList的 response 属性中
  return res.data.url
}

// 表单验证规则
const rules = ref<FormRules<AddEnterpriseData>>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '请选择行业', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入企业联系人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
})

// 创建表单实例
const addFormRef = ref<FormInstance>()

// 提交表单
const router = useRouter()
// 提交后按钮变为加载状态
const submitLoading = ref(false)
const onSubmit = async () => {
  try {
    await addFormRef.value?.validate()
    submitLoading.value = true
    if (route.params.id) {
      await editEnterpriseAPI({
        ...addForm.value,
        id: +route.params.id
      })
      ElMessage.success('编辑成功')
    } else {
      await addEnterpriseAPI(addForm.value)
      ElMessage.success('添加成功')
    }
    router.back()
  } catch (error) {
    submitLoading.value = false
    console.log(error);
  }
}
// 重置表单
const onReset = () => {
  addFormRef.value?.resetFields()
}

// 编辑功能
const route = useRoute()
onMounted(async () => {
  if (route.params.id) {
    const res = await getEnterpriseDetailAPI(route.params.id as string)
    const { name, legalPerson, registeredAddress, industryCode, contact, contactNumber, businessLicenseUrl, businessLicenseId } = res.data
    // 数据回显
    addForm.value = { name, legalPerson, registeredAddress, industryCode, contact, contactNumber, businessLicenseUrl, businessLicenseId }
    // 回显图片
    fileList.value = [{ url: businessLicenseUrl, name: '' }]
  }
})

</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id ? '编辑企业' : '添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryList" :key="item.industryCode" :label="item.industryName"
                  :value="item.industryCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" maxlength="11" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload v-model:file-list="fileList" list-type="picture" :http-request="uploadFile" :limit="1"
                accept=".png, .jpg, .jpeg" :before-upload="beforeUpload" :on-remove="removeFile">
                <el-button v-if="fileList.length === 0" type="primary" :icon="Upload">点击上传</el-button>
                <el-button v-else type="success" disabled :icon="CircleCheck">已上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          {{ addForm }}
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>